//
//  PostQuestionViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/9/25.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "PostQuestionViewController.h"

#import "TZImagePickerController.h"
#import "SelectImgCollectionViewCell.h"
#import "LnviteExpertsCell.h"

#import "User.h"

#import "ISRDataHelper.h"
#import "IATConfig.h"
#import "AlertSeleView.h"


@interface PostQuestionViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, TZImagePickerControllerDelegate, UITextFieldDelegate, UITextViewDelegate, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate> {
    // 选图片
    CGFloat _itemWH;
    CGFloat _margin;
}

@property (nonatomic ,strong) NSMutableArray *photosArray;
@property (nonatomic ,strong) NSMutableArray *assestArray;
@property BOOL isSelectOriginalPhoto;


@property (nonatomic, assign) NSInteger page; //网络请求页数
@property (nonatomic, strong) NSMutableArray *expertsArr; // 专家数组

@property (nonatomic, strong) NSMutableArray *selectExpertsArr; // 选中专家

@property (nonatomic, strong) NSString *keyWord;

@property (nonatomic, strong) NSMutableString *scopeStr;

@property (nonatomic, strong) NSString *imgStr;

@end

@implementation PostQuestionViewController {
    
    UITextField *_textField;
    UITextView  *_textView;
    UICollectionView *_collectionView;
    UITableView *_tableView;
    LnviteExpertsCell   *_cell;
    
    UIView      *_tableHeadView;
    UIView      *_middleBgView;
    UIView      *_moneyBgView;
    UILabel     *_money;
    
    UIView      *_scopeBgView;
    UILabel     *_scope;
    
    UIView      *_searchBarBgView;
    UISearchBar *_searchBar;
    UISearchBar *_searchBar2; // 点击搜索弹出之后的搜索框
    
    UIView      *_tableHeadView2;
    
    NSRange     _range;
}


-(void)viewWillAppear:(BOOL)animated
{
    //    NSLog(@"%s",__func__);
    
    [super viewWillAppear:animated];
    
    [self initRecognizer];
}



-(void)viewWillDisappear:(BOOL)animated
{
    //    NSLog(@"%s",__func__);
    
    if ([IATConfig sharedInstance].haveView == NO) {
        
        [_iFlySpeechRecognizer cancel];
        [_iFlySpeechRecognizer setDelegate:nil];
        [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        [_pcmRecorder stop];
        _pcmRecorder.delegate = nil;
    }
    else
    {
        [_iflyRecognizerView cancel];
        [_iflyRecognizerView setDelegate:nil];
        [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
    }
    
    
    [super viewWillDisappear:animated];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.page = 1;
    self.keyWord = @"";
    self.imgStr = @"";
    
    // 获取关注列表
    [self GETExperts];
    
    [self buildUI];
    
}

#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.view.backgroundColor = UISeparatedColorRGB;
    UIView *navView;
    if (self.type) {
        navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
        [self.view addSubview:navView];
        navView.backgroundColor = UIMainColorRGB;
        
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:cancelBtn];
        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        cancelBtn.titleLabel.font = kUHSystemFontWithSize(14);
        [cancelBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
        cancelBtn.frame = CGRectMake(0, 20, 50, 44);
        [cancelBtn addTarget:self action:@selector(cancelPostClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:sendBtn];
        [sendBtn setTitle:@"发表" forState:UIControlStateNormal];
//        [sendBtn setImage:IMAGE(@"return") forState:UIControlStateNormal];
        sendBtn.titleLabel.font = kUHSystemFontWithSize(14);
        [sendBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
        sendBtn.frame = CGRectMake(SCREEN_WIDTH-50, 20, 50, 44);
        [sendBtn addTarget:self action:@selector(navRithAction:) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(self.view.centerX-50, 20, 100, 44)];
        [self.view addSubview:titleL];
        titleL.textAlignment = NSTextAlignmentCenter;
        titleL.textColor = kWhiteColor;
        titleL.font = kUHSystemFontWithSize(15);
        titleL.text = @"发布";
        
    }
    
    else {
    
    self.navigationItem.title = @"发布";
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发表" style:UIBarButtonItemStylePlain target:self action:@selector(navRithAction:)];
    
    }
    _tableHeadView = [[UIView alloc] init];
    _tableHeadView2 = [[UIView alloc] init];
    
    
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    [_tableHeadView addSubview:_textField];
    _textField.backgroundColor = kWhiteColor;
//    _textField.delegate = self;
    _textField.placeholder = @"标题";
    _textField.delegate = self;
    _textField.font = kUHSystemFontWithSize(14);
    UIView *leftV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
    _textField.leftViewMode = UITextFieldViewModeAlways;
    _textField.leftView = leftV;
    
    
    // 包含 textView collectionView label
    _middleBgView = [[UIView alloc] init];
    [_tableHeadView addSubview:_middleBgView];
    _middleBgView.backgroundColor = kWhiteColor;
    
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH-20, 100)];
    [_middleBgView addSubview:_textView];
    _textView.font = kUHSystemFontWithSize(14);
    _textView.textColor = kBlackColor;
    _textView.text = @"";
    _textView.delegate = self;
    
    UIButton *yuyinBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_middleBgView addSubview:yuyinBtn];
    yuyinBtn.titleLabel.font = kUHSystemFontWithSize(14);
    yuyinBtn.frame = CGRectMake(SCREEN_WIDTH-100, _textView.y+_textView.height, 80, 44);
    [yuyinBtn setBackgroundColor:UIMainColorRGB];
    [yuyinBtn setTitle:@"语音输入" forState:UIControlStateNormal];
    [yuyinBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [yuyinBtn addTarget:self action:@selector(voiceClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *picLimit = [[UILabel alloc] initWithFrame:CGRectMake(10, yuyinBtn.y+yuyinBtn.height, SCREEN_WIDTH-20, [LZCTools textSizeWithText:@"x" font:kUHSystemFontWithSize(12)].height)];
    [_middleBgView addSubview:picLimit];
    picLimit.text = @"最多上传三张";
    picLimit.font = kUHSystemFontWithSize(12);
    picLimit.textColor = kBlackColor;
    
    // 构建 UICollectionView
    _margin = 3;
    _itemWH = (self.view.bounds.size.width - 2 * _margin - 3) / 2 - _margin;
    UICollectionViewFlowLayout *flowLayOut = [[UICollectionViewFlowLayout alloc] init];
    flowLayOut.itemSize = CGSizeMake((SCREEN_WIDTH - 50)/ 3, (SCREEN_WIDTH - 50)/ 3);
    flowLayOut.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, picLimit.y+picLimit.height, SCREEN_WIDTH,  (SCREEN_WIDTH - 50)/3+20) collectionViewLayout:flowLayOut];
    
    _collectionView.backgroundColor = kWhiteColor;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_middleBgView addSubview:_collectionView];
    
    [_collectionView registerClass:[SelectImgCollectionViewCell class] forCellWithReuseIdentifier:@"pic"];
    
    _middleBgView.frame = CGRectMake(0, _textField.height+10, SCREEN_WIDTH, _collectionView.y+_collectionView.height);
    
    // money
    _moneyBgView = [[UIView alloc] initWithFrame:CGRectMake(0, _middleBgView.y+_middleBgView.height+10, SCREEN_WIDTH, 44)];
    [_tableHeadView addSubview:_moneyBgView];
    _moneyBgView.backgroundColor = kWhiteColor;

    UILabel *moneyL = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, SW(2), _moneyBgView.height)];
    [_moneyBgView addSubview:moneyL];
    moneyL.textColor = kBlackColor;
    moneyL.text = @"悬赏金额";
    moneyL.font = kUHSystemFontWithSize(14);
    
    _money = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-_moneyBgView.height-100, 0, 100, _moneyBgView.height)];
    [_moneyBgView addSubview:_money];
    _money.textColor = kLightGrayColor;
    _money.font = kUHSystemFontWithSize(14);
    _money.text = @"0元";
    _money.textAlignment = NSTextAlignmentRight;
    
    UIButton *moneyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_moneyBgView addSubview:moneyBtn];
    [moneyBtn setImage:IMAGE(@"arrow_right_grey") forState:UIControlStateNormal];
    moneyBtn.frame = CGRectMake(SCREEN_WIDTH-_moneyBgView.height, 0, _moneyBgView.height, _moneyBgView.height);
    
    [_moneyBgView addTarget:self action:@selector(inputMoneyClick:)];
    
//    self.scopeStr = [NSMutableString stringWithFormat:@"all"];
    
    // scope
    _scopeBgView = [[UIView alloc] init];
    int state = [LZCTools thinkEnv];
    if (state == 1) {
        //        _searchBarBgView = [[UIView alloc] initWithFrame:CGRectMake(0, _moneyBgView.y+_moneyBgView.height+10, SCREEN_WIDTH, 84)];
        _scopeBgView.frame = CGRectMake(0, _moneyBgView.y+_moneyBgView.height+10, SCREEN_WIDTH, 44);
    }
    else {
        _moneyBgView.hidden = YES;
        _scopeBgView.frame = CGRectMake(0, _middleBgView.y+_middleBgView.height+10, SCREEN_WIDTH, 44);
        //        _searchBarBgView = [[UIView alloc] initWithFrame:CGRectMake(0, _middleBgView.y+_middleBgView.height+10, SCREEN_WIDTH, 84)];
    }
    [_tableHeadView addSubview:_scopeBgView];
    _scopeBgView.backgroundColor = kWhiteColor;
    
    UILabel *scopeL = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, SW(2), _scopeBgView.height)];
    [_scopeBgView addSubview:scopeL];
    scopeL.textColor = kBlackColor;
    scopeL.text = @"回答身份";
    scopeL.font = kUHSystemFontWithSize(14);
    
    _scope = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-_scopeBgView.height-100, 0, 100, _scopeBgView.height)];
    [_scopeBgView addSubview:_scope];
    _scope.textColor = kLightGrayColor;
    _scope.font = kUHSystemFontWithSize(14);
    _scope.text = @"所有人";
    _scope.textAlignment = NSTextAlignmentRight;
    
    UIButton *scopeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_scopeBgView addSubview:scopeBtn];
    [scopeBtn setImage:IMAGE(@"arrow_right_grey") forState:UIControlStateNormal];
    scopeBtn.frame = CGRectMake(SCREEN_WIDTH-_scopeBgView.height, 0, _scopeBgView.height, _scopeBgView.height);
    
    [_scopeBgView addTarget:self action:@selector(inputScopeClick:)];
    
    
    _searchBarBgView = [[UIView alloc] initWithFrame:CGRectMake(0, _scopeBgView.y+_scopeBgView.height+10, SCREEN_WIDTH, 84)];
    [_tableHeadView addSubview:_searchBarBgView];
    _searchBarBgView.backgroundColor = kWhiteColor;
    
    UILabel *expertL = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-20, 44)];
    [_searchBarBgView addSubview:expertL];
    expertL.text = @"推荐邀约专家";
    expertL.textColor = kBlackColor;
    expertL.font = kUHSystemFontWithSize(14);
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(0, expertL.height, SCREEN_WIDTH, 1)];
    [_searchBarBgView addSubview:line2];
    line2.backgroundColor = UISeparatedColorRGB;
    
    
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 54, SCREEN_WIDTH, 30)];
    _searchBar.delegate = self;
    [_searchBarBgView addSubview:_searchBar];
    _searchBar.placeholder = @"请输入搜索内容…";
    _searchBar.backgroundImage = IMAGE(@"clearImage");
    _searchBar.layer.cornerRadius = _searchBar.height/2;
    _searchBar.layer.masksToBounds = YES;
    UIView *searchTextField = searchTextField = [_searchBar valueForKey:@"_searchField"];
    searchTextField.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1];
//    UIView *searView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _searchBar.width, _searchBar.height)];
//    [_searchBar addSubview:searView];
//    [searView addTarget:self action:@selector(searchClicK:)];
    
    
    _searchBar2 = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 30)];
    [_tableHeadView2 addSubview:_searchBar2];
    _searchBar2.delegate = self;
    _searchBar2.placeholder = @"请输入搜索内容…";
    _searchBar2.backgroundImage = IMAGE(@"clearImage");
    _searchBar2.layer.cornerRadius = _searchBar.height/2;
    _searchBar2.layer.masksToBounds = YES;
    UIView *searchTextField2 = searchTextField = [_searchBar2 valueForKey:@"_searchField"];
    searchTextField2.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1];
   
    _tableHeadView.frame = CGRectMake(0, 0, SCREEN_WIDTH, _searchBarBgView.y+_searchBarBgView.height);
    _tableHeadView2.frame = CGRectMake(0, 0, SCREEN_WIDTH, _searchBar2.height+_searchBar2.y);
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    if (self.type) {
        _tableView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64);
    }
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableHeaderView = _tableHeadView;
    //    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.tableFooterView = [[UIView alloc]init];
    [_tableView registerNib:[UINib nibWithNibName:@"LnviteExpertsCell" bundle:nil] forCellReuseIdentifier:@"experts"];
    _tableHeadView.backgroundColor = UISeparatedColorRGB;
    
}


#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETExperts];
    }];
    
}


#pragma mark ==========UISearchBar 代理响应方法==========
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    return YES;
}
//- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
//    return YES;
//}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    NSLog(@"开始输入搜索内容");
    
    // 取消字体颜色？
    searchBar.showsCancelButton = YES;
    [searchBar setShowsCancelButton:YES animated:YES];
//    [searchBar becomeFirstResponder];
    if ([searchBar isEqual:_searchBar]) {
        _tableView.tableHeaderView = _tableHeadView2;
//        [_searchBar2 becomeFirstResponder];
    }
    
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    NSLog(@"输入搜索完毕");
    
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"取消搜索");
    
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
    
    if ([searchBar isEqual:_searchBar2]) {
        _tableView.tableHeaderView = _tableHeadView;
    }
    
    self.keyWord = @"";
    self.page = 1;
    [self GETExperts];
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"搜索");
    
    NSString *word = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (word.length == 0) {
        [self presentViewController:[LZCTools alertMessage:@"请输入关键字"] animated:YES completion:nil];
        return;
    }
    
    self.keyWord = word;
    
    [searchBar resignFirstResponder];
    
    [self GETExperts];
}

#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    _cell = [tableView dequeueReusableCellWithIdentifier:@"experts"];
    
    _cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    User *model = self.expertsArr[indexPath.row];
    _cell.model = model;
    
    NSString *uId = [NSString stringWithFormat:@"%ld", model.user_id];
    if ([self.selectExpertsArr containsObject:uId]) {
        _cell.invitation.selected = YES;
        [_cell.invitation setBackgroundColor:kLightGrayColor];
    }
    else {
        _cell.invitation.selected = NO;
        [_cell.invitation setBackgroundColor:UIMainColorRGB];
    }
    
    _cell.invitation.tag = indexPath.row+1;
    [_cell.invitation addTarget:self action:@selector(invitaAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return _cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.expertsArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return SW(10)+20;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
}


#pragma mark ==========UICollectionView 响应代理============

- (void)checkLocalPhoto{
    
    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:3 delegate:self];
    [imagePicker setSortAscendingByModificationDate:NO];
    imagePicker.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    imagePicker.selectedAssets = _assestArray;
    imagePicker.allowPickingVideo = NO;
    [self presentViewController:imagePicker animated:YES completion:nil];
    
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    self.photosArray = [NSMutableArray arrayWithArray:photos];
    self.assestArray = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    [_collectionView reloadData];
    
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == _photosArray.count) {
        [self checkLocalPhoto];
    }else{
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_assestArray selectedPhotos:_photosArray index:indexPath.row];
        imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            _photosArray = [NSMutableArray arrayWithArray:photos];
            _assestArray = [NSMutableArray arrayWithArray:assets];
            _isSelectOriginalPhoto = isSelectOriginalPhoto;
            [_collectionView reloadData];
            _collectionView.contentSize = CGSizeMake(0, ((_photosArray.count + 2) / 3 ) * (_margin + _itemWH));
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
//    if (_photosArray.count < 3) {
//        _collectionView.frame = CGRectMake(0, _textView.height+_textView.y, SCREEN_WIDTH, (SCREEN_WIDTH - 50)/3+20);
//    }
//    else if (_photosArray.count < 6) {
//        _collectionView.frame = CGRectMake(0, _textView.height+_textView.y, SCREEN_WIDTH, (SCREEN_WIDTH - 50)/3*2+30);
//    }
//    else
//        _collectionView.frame = CGRectMake(0, _textView.height+_textView.y, SCREEN_WIDTH, (SCREEN_WIDTH - 50)/3*3+40);
    
    return _photosArray.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SelectImgCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pic" forIndexPath:indexPath];
    
    if (indexPath.row == _photosArray.count) {
        cell.imagev.image = [UIImage imageNamed:@"AlbumAddBtn@2x"];
        //        cell.imagev.backgroundColor = [UIColor redColor];
        cell.deleteButton.hidden = YES;
        
    }else{
        cell.imagev.image = _photosArray[indexPath.row];
        cell.deleteButton.hidden = NO;
    }
    cell.deleteButton.tag = 100 + indexPath.row;
    [cell.deleteButton addTarget:self action:@selector(deletePhotos:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
    
}

- (void)deletePhotos:(UIButton *)sender{
    [_photosArray removeObjectAtIndex:sender.tag - 100];
    [_assestArray removeObjectAtIndex:sender.tag - 100];
    [_collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag-100 inSection:0];
        [_collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [_collectionView reloadData];
    }];
}


#pragma mark ===========响应方法==========
- (void)GETExperts {
    // GET /users/{uid}/favorites 获取关注的人 uid *关注人ID
    // GET /users/{uid}/fans 获取粉丝 uid *被关注人I
    
    NSString *uId = [GetUserDefaule(USERINFO) valueForKey:@"user_id"];
    
    NSString *url = [NSString stringWithFormat:@"%@/%@/favorites", APIUser, uId];
    
    NSDictionary *param = @{@"per_page":@"10",
                            @"page":[NSString stringWithFormat:@"%ld", self.page],
                            @"role":@"3",
                            @"keyword":self.keyWord};
    
    // 3 是专家
    [[NetworkTool sharedTool] requestWithName:@"获取关注的人" URLString:url parameters:param method:@"GET" callBack:^(id responseObject) {
        NSArray *arr = responseObject[@"data"];
        
        if (self.page == 1) {
            [self.expertsArr removeAllObjects];
        }
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
        }
        for (NSDictionary *dic in arr) {
            User *model = [[User alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.expertsArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];
        });
    }];
}

- (void)invitaAction:(UIButton *)sender {
    NSLog(@"邀约专家");
    sender.selected = !sender.isSelected;
    
    if (sender.selected) {
        [sender setBackgroundColor:kLightGrayColor];
    }
    else
        [sender setBackgroundColor:UIMainColorRGB];
    
    
    User *model = self.expertsArr[sender.tag-1];
    NSString *uid = [NSString stringWithFormat:@"%ld", model.user_id];
    if (![self.selectExpertsArr containsObject:uid]) {
        [self.selectExpertsArr addObject:uid];
    }
    else
        [self.selectExpertsArr removeObject:uid];
}

/**
 导航右按钮
 */
- (void)navRithAction:(id)sender {
    NSLog(@"发表问题");
    
    if (self.photosArray.count == 0) {
        [self post];
        return;
    }
    
    NSDictionary *dict = @{
                           @"file[]":@[]
                           };
    
    AFHTTPSessionManager *afn = [AFHTTPSessionManager manager];
    
    // 请求头
    [afn.requestSerializer setValue:[GetUserDefaule(Token) valueForKey:@"access_token"]forHTTPHeaderField:@"Authorization"];
    
    [afn POST:APIImages parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
        // 这里的_photoArr是你存放图片的数组
        for (int i = 0; i < self.photosArray.count; i++) {
            
            UIImage *image = self.photosArray[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
            
            // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
            // 要解决此问题，
            // 可以在上传时使用当前的系统事件作为文件名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
            /*
             *该方法的参数
             1. appendPartWithFileData：要上传的照片[二进制流]
             2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
             3. fileName：要保存在服务器上的文件名
             4. mimeType：上传的文件的类型
             */
            [formData appendPartWithFileData:imageData name:@"pic[]" fileName:fileName mimeType:@"image/jpeg"]; //
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id obj = [JWT decodeMessage:responseObject[@"token"]].secret(JWTSecret).algorithmName(@"HS256").decode;
        //        return [obj valueForKey:@"payload"];
        NSArray *imgArr = [[[obj valueForKey:@"payload"] valueForKey:@"data"] valueForKey:@"images"];
        NSLog(@"上传图片 success = %@", imgArr);
        
        self.imgStr = [imgArr componentsJoinedByString:@","];
        
        [self post];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传图片 failure = %@", error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self presentViewController:[LZCTools AFNErrorAlert:error] animated:YES completion:nil];
    }];
    
}

- (void)post {
    
    // POST /questions 添加问题 title *标题 body *问题描述 reward 悬赏金，单位分 pics 附加图片，多张以逗号隔开 invitees 邀请的用户ID，多个以逗号隔开
    NSString *m = [_money.text componentsSeparatedByString:@"元"][0];
    NSString *money = [NSString stringWithFormat:@"%lf", [m floatValue]*100]; // 后台逻辑 * 100
    NSString *scopeS;
    if ([_scope.text isEqualToString:@"所有人"]) {
        scopeS = @"all";
    }
    else
        scopeS = @"pro";
    
    NSDictionary *param = @{@"title":_textField.text,
                            @"body":_textView.text,
                            @"pics":self.imgStr,
                            @"invitees":[self.selectExpertsArr componentsJoinedByString:@","],
                            @"reward":money,
                            @"scope":scopeS};
    
    
    [[NetworkTool sharedTool] requestWithName:@"发表问题" URLString:APIQuestions parameters:param method:@"POST" callBack:^(id responseObject) {
        
        if (self.type) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        else
            [self.navigationController popViewControllerAnimated:YES];
        
    }];
}

- (void)inputScopeClick:(id)sender {
    NSLog(@"弹出身份选择框");
    
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"回答身份" message:nil preferredStyle:UIAlertControllerStyleAlert];
//    [alert addAction:[UIAlertAction actionWithTitle:@"专家" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        self.scopeStr = @"pro";
//        _scope.text = @"专家";
//    }]];
//    [alert addAction:[UIAlertAction actionWithTitle:@"所有人" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        self.scopeStr = @"all";
//        _scope.text = @"所有人";
//    }]];
//    [self presentViewController:alert animated:YES completion:nil];
    
    AlertSeleView *alert = [[AlertSeleView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
//    [alert initShow:dic];
    //        [self.view addSubview:alert];
//    [alert initShow:_scope str:self.scopeStr];
    [alert initShow:_scope];
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    [window addSubview:alert];
    
}

- (void)inputMoneyClick:(id)sender {
    NSLog(@"弹出金额输入框");
    //输入框
    NSString *title = @"悬赏金额";
//    NSString *message = @"money";
    NSString *okButtonTitle = @"确定";
    
    // 初始化
    UIAlertController *alertDialog = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];

    // 创建文本框
    [alertDialog addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.placeholder = @"请输入悬赏金额";
        textField.secureTextEntry = NO;
        textField.keyboardType = UIKeyboardTypeDecimalPad;
    }];
    // 创建操作
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:okButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    // 读取文本框的值显示出来
    UITextField *userEmail = alertDialog.textFields.firstObject;
    if ([userEmail.text isEqualToString:@""]) {
        _money.text = @"0元";
    }
    else
        _money.text = [NSString stringWithFormat:@"%@元", userEmail.text];
    }];
    // 添加操作（顺序就是呈现的上下顺序）
    [alertDialog addAction:okAction];
    
    [self presentViewController:alertDialog animated:YES completion:nil];
}

// 取消发布
- (void)cancelPostClick:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark ===========代理方法==========
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}


- (void)textViewDidChangeSelection:(UITextView *)textView {
    
    _range = textView.selectedRange;
    NSLog(@"range  %lu", (unsigned long)_range.length);
    NSLog(@"range  %lu", (unsigned long)_range.location);
}




// 懒加载
- (NSMutableArray *)photosArray{
    if (!_photosArray) {
        self.photosArray = [NSMutableArray array];
    }
    return _photosArray;
}

- (NSMutableArray *)assestArray{
    if (!_assestArray) {
        self.assestArray = [NSMutableArray array];
    }
    return _assestArray;
}

- (NSMutableArray *)expertsArr {
    if (_expertsArr == nil) {
        _expertsArr = [[NSMutableArray alloc] init];
    }
    return _expertsArr;
}

- (NSMutableArray *)selectExpertsArr {
    if (_selectExpertsArr == nil) {
        _selectExpertsArr = [[NSMutableArray alloc] init];
    }
    return _selectExpertsArr;
}

#pragma mark =========讯飞

- (void)voiceClick:(UIButton *)btn {
    
    [IATConfig sharedInstance].haveView = YES;
    
    if ([IATConfig sharedInstance].haveView == NO) {
        
        //        [_textView setText:@""];
        
        
        if ([_textView.text isEqualToString:@"你想说点什么？"]) {
            _textView.text =@"";
            _textView.textColor = kBlackColor;
        }
        
        
        [_textView resignFirstResponder];
        self.isCanceled = NO;
        self.isStreamRec = NO;
        
        if(_iFlySpeechRecognizer == nil)
        {
            [self initRecognizer];
        }
        
        [_iFlySpeechRecognizer cancel];
        
        //Set microphone as audio source
        [_iFlySpeechRecognizer setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
        
        //Set result type
        [_iFlySpeechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];
        
        //Set the audio name of saved recording file while is generated in the local storage path of SDK,by default in library/cache.
        [_iFlySpeechRecognizer setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        
        [_iFlySpeechRecognizer setDelegate:self];
        
        BOOL ret = [_iFlySpeechRecognizer startListening];
        
        if (ret) {
            
        }else{
            //            [_popUpView showText: NSLocalizedString(@"M_ISR_Fail", nil)];//Last session may be not over, recognition not supports concurrent multiplexing.
        }
    }else {
        
        if(_iflyRecognizerView == nil)
        {
            [self initRecognizer ];
        }
        
        //        [_textView setText:@""];
        if ([_textView.text isEqualToString:@"你想说点什么？"]) {
            _textView.text =@"";
            _textView.textColor = kBlackColor;
        }
        
        [_textView resignFirstResponder];
        
        //Set microphone as audio source
        [_iflyRecognizerView setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
        
        //Set result type
        [_iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
        
        //Set the audio name of saved recording file while is generated in the local storage path of SDK,by default in library/cache.
        [_iflyRecognizerView setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        
        BOOL ret = [_iflyRecognizerView start];
        if (ret) {
        }
    }
}


#pragma mark - IFlySpeechRecognizerDelegate

/**
 volume callback,range from 0 to 30.
 **/
- (void) onVolumeChanged: (int)volume
{
    
}



/**
 Beginning Of Speech
 **/
- (void) onBeginOfSpeech
{
    NSLog(@"onBeginOfSpeech");
}

/**
 End Of Speech
 **/
- (void) onEndOfSpeech
{
    NSLog(@"onEndOfSpeech");
    
    [_pcmRecorder stop];
}


/**
 recognition session completion, which will be invoked no matter whether it exits error.
 error.errorCode =
 0     success
 other fail
 **/
- (void) onError:(IFlySpeechError *) error
{
    NSLog(@"%s",__func__);
    
    if ([IATConfig sharedInstance].haveView == NO ) {
        
        NSString *text ;
        
        if (self.isCanceled) {
            text = NSLocalizedString(@"T_ISR_Cancel", nil);
            
        } else if (error.errorCode == 0 ) {
            if (_result.length == 0) {
                text = NSLocalizedString(@"T_ISR_NoRlt", nil);
            }else {
                text = NSLocalizedString(@"T_ISR_Succ", nil);
                //empty results
                _result = nil;
            }
        }else {
            text = [NSString stringWithFormat:@"Error：%d %@", error.errorCode,error.errorDesc];
            NSLog(@"%@",text);
        }
        
        
    }else {
        NSLog(@"errorCode:%d",[error errorCode]);
    }
    
}

/**
 result callback of recognition without view
 results：recognition results
 isLast：whether or not this is the last result
 **/
- (void) onResults:(NSArray *) results isLast:(BOOL)isLast
{
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    
    _result =[NSString stringWithFormat:@"%@%@", _textView.text,resultString];
    NSString * resultFromJson =  [ISRDataHelper stringFromJson:resultString];
    _textView.text = [NSString stringWithFormat:@"%@%@", _textView.text,resultFromJson];
    
    if (isLast){
        NSLog(@"ISR Results(json)：%@",  self.result);
    }
    NSLog(@"_result=%@",_result);
    NSLog(@"resultFromJson=%@",resultFromJson);
    NSLog(@"isLast=%d,_textView.text=%@",isLast,_textView.text);
}

/**
 result callback of recognition with view
 resultArray：recognition results
 isLast：whether or not this is the last result
 **/
- (void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast
{
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    
    NSLog(@"range  %lu", (unsigned long)_range.location);
    
    // 如果光标小于，就做处理
    if (_range.location < _textView.text.length) {
        
        NSString *str1 = [_textView.text substringToIndex:_range.location];//截取掉下标5之前的字符串
        NSString *str2 = [_textView.text substringFromIndex:_range.location];//截取掉下标3之后的字符串
        _textView.text = [NSString stringWithFormat:@"%@%@%@", str1, result, str2];
    }
    else
        _textView.text = [NSString stringWithFormat:@"%@%@",_textView.text,result];
}



/**
 callback of canceling recognition
 **/
- (void) onCancel
{
    NSLog(@"Recognition is cancelled");
}

-(void) showPopup
{
    //    [_popUpView showText: NSLocalizedString(@"T_ISR_Uping", nil)];
}

#pragma mark - IFlyDataUploaderDelegate

/**
 result callback of uploading contacts or customized words
 **/
- (void) onUploadFinished:(IFlySpeechError *)error
{
    NSLog(@"%d",[error errorCode]);
    
    if ([error errorCode] == 0) {
        //        [_popUpView showText: NSLocalizedString(@"T_ISR_UpSucc", nil)];
    }
    else {
        //        [_popUpView showText: [NSString stringWithFormat:@"%@:%d", NSLocalizedString(@"T_ISR_UpFail", nil), error.errorCode]];
        
    }
    
}


#pragma mark - Initialization

/**
 initialize recognition conctol and set recognition params
 **/
-(void)initRecognizer
{
    NSLog(@"%s",__func__);
    
    if ([IATConfig sharedInstance].haveView == NO) {
        
        //recognition singleton without view
        if (_iFlySpeechRecognizer == nil) {
            _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
        }
        
        [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        //set recognition domain
        [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        
        _iFlySpeechRecognizer.delegate = self;
        
        if (_iFlySpeechRecognizer != nil) {
            IATConfig *instance = [IATConfig sharedInstance];
            
            //set timeout of recording
            [_iFlySpeechRecognizer setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
            //set VAD timeout of end of speech(EOS)
            [_iFlySpeechRecognizer setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
            //set VAD timeout of beginning of speech(BOS)
            [_iFlySpeechRecognizer setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
            //set network timeout
            [_iFlySpeechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
            
            //set sample rate, 16K as a recommended option
            [_iFlySpeechRecognizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
            
            //set language
            [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            //set accent
            [_iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
            
            //set whether or not to show punctuation in recognition results
            [_iFlySpeechRecognizer setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
            
        }
        
        //Initialize recorder
        if (_pcmRecorder == nil)
        {
            _pcmRecorder = [IFlyPcmRecorder sharedInstance];
        }
        
        _pcmRecorder.delegate = self;
        
        [_pcmRecorder setSample:[IATConfig sharedInstance].sampleRate];
        
        [_pcmRecorder setSaveAudioPath:nil];    //not save the audio file
        
    }else  {
        
        //recognition singleton with view
        if (_iflyRecognizerView == nil) {
            
            _iflyRecognizerView= [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
        }
        
        [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        //set recognition domain
        [_iflyRecognizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        
        
        _iflyRecognizerView.delegate = self;
        
        if (_iflyRecognizerView != nil) {
            IATConfig *instance = [IATConfig sharedInstance];
            //set timeout of recording
            [_iflyRecognizerView setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
            //set VAD timeout of end of speech(EOS)
            [_iflyRecognizerView setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
            //set VAD timeout of beginning of speech(BOS)
            [_iflyRecognizerView setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
            //set network timeout
            [_iflyRecognizerView setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
            
            //set sample rate, 16K as a recommended option
            [_iflyRecognizerView setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
            
            //set language
            [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            //set accent
            [_iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
            //set whether or not to show punctuation in recognition results
            [_iflyRecognizerView setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
            
        }
    }
}




-(void)setExclusiveTouchForButtons:(UIView *)myView
{
    for (UIView * button in [myView subviews]) {
        if([button isKindOfClass:[UIButton class]])
        {
            [((UIButton *)button) setExclusiveTouch:YES];
        }
        else if ([button isKindOfClass:[UIView class]])
        {
            [self setExclusiveTouchForButtons:button];
        }
    }
}


#pragma mark - IFlyPcmRecorderDelegate

- (void) onIFlyRecorderBuffer: (const void *)buffer bufferSize:(int)size
{
    NSData *audioBuffer = [NSData dataWithBytes:buffer length:size];
    
    int ret = [self.iFlySpeechRecognizer writeAudio:audioBuffer];
    if (!ret)
    {
        [self.iFlySpeechRecognizer stopListening];
    }
}

- (void) onIFlyRecorderError:(IFlyPcmRecorder*)recoder theError:(int) error
{
    
}

//range from 0 to 30
- (void) onIFlyRecorderVolumeChanged:(int) power
{
    //    NSLog(@"%s,power=%d",__func__,power);
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
